package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.enums.PlayState;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.CartoonVo;
import com.jdy.haoduoaiteacher.model.HotSearchKey;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.LeConfig;
import com.jdy.haoduoaiteacher.util.LePreference;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.view.MusicPlayView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.util.HashMap;

//import com.jdy.haoduoaiteacher.R;

/**
 * 
 * @author hufei
 * 
 */
@SuppressLint("HandlerLeak")
public class RadioDetailActivity extends BaseActivity implements
    OnClickListener {

  @InjectView(id = R.id.layout_media_play_view)
  private MusicPlayView mPlayView;

  @InjectView(id = R.id.btn_play_pause, click = true)
  private Button mPlayPause;

  @InjectView(id = R.id.btn_next, click = true)
  private Button mNext;

  @InjectView(id = R.id.btn_previous, click = true)
  private Button mPrevious;
  @InjectView(id = R.id.tv_radio_abs)
  private TextView tv_radio_abs;

  @InjectView(id = R.id.tv_playcount)
  private TextView tv_playcount;

  @InjectView(id = R.id.tv_author)
  private TextView tv_author;

  private String imageUrl;
  private ImageView imageCover;
  @SuppressWarnings("unused")
  private int mResource;

  private boolean isPlayInit = false;
  @SuppressWarnings("unused")
  private boolean isPlay = false;
  private int playid;
  @SuppressWarnings("unused")
  private int sumcount, sumhit, sumzan;
  private String content;
  private String author;
  @SuppressWarnings("unused")
  private String type;
  private BroadcastReceiver mReceiver = null;
  private CartoonVo detailVo = null;
  private LeUser leUser;
  private int album_id;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.radiodetail_layout);

    initData();
    requestData();
  }

  private void requestData() {
    showloading("加载中..");
    new CustomAsyncTask(RadioDetailActivity.this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        dismissLoading();
        if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
          detailVo = JsonSerializer.getInstance().deserialize(result.data,
              CartoonVo.class);
          updateDetail();
        } else if (Tools.isNotNullStr(result.data)) {
          toastShow(result.data.toString());
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        return HttpUtils.startRequest(HttpUtils.HOST_API
            + HttpUtils.GET_CATALOG_ALBUM + "/" + album_id, param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void updateDetail() {
    setTitle(detailVo.name);
    imageUrl = detailVo.cover;
    playid = detailVo.id;
    sumcount = detailVo.total_comment;
    sumhit = detailVo.followers;
    content = detailVo.description;
    author = detailVo.author;
    type = detailVo.catalog;
    initView();
  }

  private void initData() {
    leUser = MyTeacherApp.getInstance().getUserTeacher();
    Intent intent = getIntent();
    if (intent.getIntExtra("id", -1) != -1) {
      album_id = intent.getIntExtra("id", -1);
    } else if (intent.getSerializableExtra("searchkey") != null) {
      HotSearchKey searchKey = (HotSearchKey) intent
          .getSerializableExtra("searchkey");
      album_id = searchKey.id;
    }

    int count = LePreference.getInstance().getInt("openradiodetailcount", 0);
    if (count < 5) {
      LePreference.getInstance().save("openradiodetailcount", count + 1);
    }

    IntentFilter mFilter = new IntentFilter();
    mFilter.addAction("radio.state.changed.event");
    mReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("radio.state.changed.event")) {
          int i = intent.getIntExtra("PlayState", -1);
          PlayState state = PlayState.values()[i];
          if (state.equals(PlayState.Pause) || state.equals(PlayState.Stop)) {
            isPlay = false;
            mPlayView.pause();
            mPlayPause.setBackgroundResource(R.drawable.rank_play);
          } else if (state.equals(PlayState.Playing)) {
            isPlay = true;
            mPlayView.play();
            mPlayPause.setBackgroundResource(R.drawable.rank_pause);
            if (!isPlayInit) {
              isPlayInit = true;
            }
          }
        }
      }
    };
    registerReceiver(mReceiver, mFilter);
  }

  private void initView() {
    imageCover = (ImageView) mPlayView.findViewById(R.id.avatar);

    ImageLoader.getInstance().displayImage(imageUrl, imageCover,
        MyTeacherApp.getInstance().getDisplayImageOptions());
    tv_radio_abs.setText(content);
    tv_playcount.setText(sumhit + "");
    tv_author.setText(author + "");
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn_play_pause:
      if (mPlayView.isPlay()) {
        mPlayView.pause();
        mPlayPause.setBackgroundResource(R.drawable.playimgs);

        playRadio(playid, "pause");

        Log.i("radio", "clickpause");
      } else {
        mPlayView.play();
        mPlayPause.setBackgroundResource(R.drawable.pauseimgs);

        Log.i("radio", "clickplay");

        if (!isPlayInit) {
          playRadio(playid, "radio");
          isPlayInit = true;
        } else {
          playRadio(playid, "continue");
        }
      }
      break;
    default:
      break;
    }
  }

  private void playvideo(final int sid, final String status) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          if (("cartoon").equals(status) || ("continue").equals(status)) {
            toastShow("已推送到设备播放");
            isPlay = true;
//            if (LeConfig.isDeviceConnect) {
//              toastShow("已推送到设备播放");
//              isPlay = true;
//            } else {
//              toastShow("未连接到设备，请检查设备联网情况！");
//              isPlay = false;
//            }

          } else if (("pause").equals(status)) {
            toastShow("暂停播放");
            isPlay = false;

          } else {
            toastShow(result.data);
          }
        } else {
          toastShow(result.data);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        HashMap<String, Object> param_ = new HashMap<String, Object>();

        int uid = -1, volume = -1, minutes = -1;
        param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
        param_.put(HttpUtils.TAG_OPERATION_I, status);
        param_.put(HttpUtils.TAG_TYPE_I, "cartoon");
        param_.put("mode", "im");

        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }

        param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  private void playRadio(final int sid, final String status) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          if (!isPlayInit) {
            toastShow("已推送到设备播放");
          }

          if (("radio").equals(status) || ("continue").equals(status)) {
            isPlay = true;
          } else if (("pause").equals(status)) {
            isPlay = false;
          }
//          if (LeConfig.isDeviceConnect) {
//
//            if (!isPlayInit) {
//              toastShow("已推送到设备播放");
//            }
//
//            if (("radio").equals(status) || ("continue").equals(status)) {
//              isPlay = true;
//            } else if (("pause").equals(status)) {
//              isPlay = false;
//            }
//
//          } else {
//            toastShow("未连接到设备，请检查设备联网情况！");
//          }

        } else {
          LeConfig.isDeviceConnect = false;
          toastShow("设备不在线");
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        if (mGlobalLeUser == null) {
          mGlobalLeUser = Tools.restoreLeUser();
        }

        int volume = -1, uid = -1, minutes = -1;

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
        param_.put(HttpUtils.TAG_OPERATION_I, status);
        param_.put("mode", "im");

        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }
        if (uid != -1) {
          param_.put(HttpUtils.TAG_UID_I, String.valueOf(uid));
        }
        if (volume != -1) {
          param_.put(HttpUtils.TAG_VOLUME, String.valueOf(volume));
        }
        if (minutes != -1) {
          param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(minutes));
        }
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    if (mReceiver != null) {
      unregisterReceiver(mReceiver);
      mReceiver = null;
    }
  }

}
